package com.face.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.face.RespMsg;
import com.face.server.entity.Admin;
import com.face.server.repository.AdminRepository;
import com.face.server.service.AdminService;
import com.face.server.service.UtileService;
import com.face.server.service.impl.EventLogService;
import com.mongodb.gridfs.GridFSDBFile;
import com.util.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Principal;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ryan on 2018/1/26.
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private AdminService adminService;

    @Autowired
    private EventLogService eventLogService;

    @Autowired
    UtileService utileService;

    @PostMapping(value = "/changePwd",consumes = "application/json")
    public RespMsg changePwd(@RequestBody String authAndPwd){
        return RespMsg.build(adminService.changePwd(authAndPwd));
    }

    @PostMapping(value = "/findPwd",consumes = "application/json")
    public RespMsg findPwd(@RequestBody String identityAndPhone){
        if(identityAndPhone==null){
            return RespMsg.error("不能为空");
        }else{
            return RespMsg.build(adminService.findPwd(identityAndPhone));
        }
    }

    @PostMapping("/addAdmin")
    public RespMsg addAdmin(@RequestParam String adminName,@RequestParam Boolean adminSex,
                            @RequestParam String adminPhone,@RequestParam String adminIdentity){
        return RespMsg.build(adminService.addAdmin(adminName,adminSex,adminPhone,adminIdentity));
    }

    @GetMapping("/findOne/{id}")
    public RespMsg findOne(@PathVariable String id){
        if(id==null||"".equals(id)){
            return RespMsg.error(1,"id不能为空");
        }
        return RespMsg.build(adminService.findOne(id));
    }

    @PostMapping("/editInfo")
    public RespMsg editInfo(@RequestParam String id,@RequestBody @RequestParam String adminName, @RequestParam Boolean adminSex,
                            @RequestParam String adminPhone, @RequestParam String adminIdentity
                            ){
        if(id==null||"".equals(id)){
            return RespMsg.error(1,"id不能为空");
        }
        System.out.println(id+adminName+adminSex+adminIdentity);
        return RespMsg.build(adminService.editInfo(id,adminName,adminSex,adminPhone,adminIdentity));
    }


    @DeleteMapping("/deleteOne/{id}")
    public RespMsg deleteOne(@PathVariable String id){
        if (id==null||id.equals("")) {
            return RespMsg.error(1,"id为空");
        }
        adminRepository.delete(id);
        return RespMsg.build(null);
    }


    @PutMapping("/deleteOwnBuilds/{id}")
    public RespMsg deleteOwnBuilds(@PathVariable String id){
        if (adminRepository.findOne(id)==null) {
            return RespMsg.error(-1,"未找到该管理员");
        }
        return RespMsg.build(adminService.deleteOwnBuilds(id));
    }

    @GetMapping(value = {"/searchInBuildMgt"})
    public RespMsg search(@RequestParam(required = false) String searchKey, @PageableDefault Pageable pageable){
        return RespMsg.build(adminService.listAdminsInBuildMgt(pageable,searchKey));
    }

    @PutMapping("/asignBuilds/{id}")
    public RespMsg asignBuilds(@PathVariable String id,@RequestBody(required = false)String searchData){
        return RespMsg.build(adminService.asignBuilds(id,searchData));
    }

    @PostMapping("/addToBuildMgt/{name}")
    public RespMsg addToBuildMgt(@PathVariable String name){
        if (adminRepository.findByName(name)==null) {
            return RespMsg.error(-1,"未找到该人员");
        } else if(adminRepository.findByName(name).getDormitoryNumList()!=null) {
            return RespMsg.error(-1,"已存在列表中");
        }
        return RespMsg.build(adminService.addToBuildMgt(name));
    }

    @GetMapping(value = {"/listAdmins/{searchKey}","/listAdmins"})
    public RespMsg listAdmins(@PathVariable(required = false) String searchKey){
        return RespMsg.build(adminService.listAdmins(searchKey));
    }

    @PostMapping(value = "/ajaxLogin")
    public RespMsg ajaxLogin(@RequestBody String user){
        JSONObject us= com.alibaba.fastjson.JSON.parseObject(user);
        String username=us.getString("username");
        String password=us.getString("password");
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);
            Admin admin=adminRepository.findByUsernameAndPassword(username,password);
            return RespMsg.build(admin.isSuper());
        } catch (Exception e) {
            return RespMsg.error(500,"登录失败");
        }
    }

    @GetMapping(value = "/listOwnBuilds/{id}")
    public RespMsg listOwnBuilds(@PathVariable String id){
        return RespMsg.build(adminService.listOwnBuilds(id));
    }

    @GetMapping("/listEvent/{type}")
    public RespMsg listStudentEvent(@PageableDefault(sort = "dormitoryBuildNum",size = 10000) Pageable pageable, @RequestBody(required = false) String searchData,@PathVariable int type){
        return RespMsg.build(eventLogService.listEvent(type,pageable,searchData));
    }

    @GetMapping("/file/{fileId}")
    void showFile(HttpServletResponse response,
                  @PathVariable String fileId) throws IOException {
        GridFSDBFile fsFile = utileService.getFile(fileId);
        OutputStream outputStream = response.getOutputStream();
        fsFile.writeTo(outputStream);
    }


    /**
     * 不进行图片判断
     */
    @GetMapping("/file/{fileId}/date")
    @ResponseBody
    GridFSDBFile showFileDate(@PathVariable String fileId) throws IOException {
        return utileService.getFile(fileId);
    }

    @GetMapping("/listMyEvent/{type}")
    public RespMsg listMyEvent(@PageableDefault(sort = "dormitoryBuildNum",size = 10000) Pageable pageable, @RequestBody(required = false) String searchData, @PathVariable int type, Principal principal){
        return RespMsg.build(eventLogService.listMyEvent(type,pageable,searchData,principal));
    }

    @GetMapping("/todayFluent/{type}")
    public RespMsg todayFluent(@PathVariable String type) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        List<Integer> dormitoryNumList=admin.getDormitoryNumList();
        return RespMsg.build(eventLogService.todayFluent(type, DateUtils.getMorning(),DateUtils.getTonight(),dormitoryNumList,admin.isSuper()));
    }

    @GetMapping("/listEvents")
    public RespMsg listEvents(@PageableDefault(sort = "dormitoryBuildNum") Pageable pageable,
                              @RequestParam(defaultValue = "0000-00-00") String begin,
                              @RequestParam(defaultValue = "9999-99-99") String end,
                              @RequestParam(defaultValue = "") String input,
                              @RequestParam(required = false)Integer type) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        List<Integer> dormitoryNumList=admin.getDormitoryNumList();
        return eventLogService.listEvents(pageable,begin,end,input,type,dormitoryNumList,admin.isSuper());
    }

    @PostMapping(value="/logout")
    public void logout(){
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        try {
            //退出
            SecurityUtils.getSubject().logout();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

}
